package com.hdl.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Druidutils {
    /**
     * druid工具类
     *    需求：1.返回连接对象方法
     *         2.返回连接池方法
     *         3.释放资源方法
     */

    private  static DataSource ds;

    static{
        try {
            //实现配置文件设置
            Properties pro = new Properties();
            pro.load(Druidutils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取DataSource数据库连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接对象
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource(){
        return  ds;
    }

    /**
     * 释放资源
     */
    public static void close(Statement state,Connection conn){
        close(null,state,conn);
    }

    public static void close(ResultSet rs,Statement state, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(state!=null){
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
